package pl.perseus.service.user;

import java.util.List;

import lombok.Data;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.perseus.dao.IUserAccountDao;
import pl.perseus.dao.IUserClassesDao;
import pl.perseus.dao.IUserDao;
import pl.perseus.model.Classes;
import pl.perseus.model.User;
import pl.perseus.model.UserAccount;
import pl.perseus.service.exception.LoginException;

@Data
@Service
@Transactional
public class UserService implements IUserService{

	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private IUserAccountDao userAccountDao;
	
	@Autowired
	private IUserClassesDao userClassesDao;
	
	@Override
	public User getById(Long id){
		return userDao.getById(id);
	}
	
	@Override
	public void logIn(String login, String passwd) throws LoginException{
		User u = userDao.selectByLoginUser(login);
		if(u == null || !u.getPassword().equals(DigestUtils.md5Hex(passwd))) throw new LoginException();
	}
	
	@Override
	public User selectUserByLogin(String login){
		return userDao.selectByLoginUser(login);
	}
	
	@Override
	public User insertUser(User u){
		return userDao.insertUser(u);
	}
	
	@Override
	public void deleteUser(User u){
		userClassesDao.deleteByUser(u);
		userAccountDao.deleteByUser(u);
		userDao.deleteUser(u);
	}
	
	@Override
	public User updateUser(User u){
		u.setActive(true);
		u.setPassword(DigestUtils.md5Hex(u.getPassword()));
		return userDao.updateUser(u);
	}
	
	@Override
	public void insertUserWithRole(User u, UserAccount a){
		User ex = selectUserByLogin(u.getLogin());
		if(null != ex) return;
		u.setPassword(DigestUtils.md5Hex(u.getLogin()));
		u.setActive(true);
		u = insertUser(u);
		a.setId_user(u.getId());
		userAccountDao.insertUserAccount(a);
	}
	
	@Override
	public List<User> getAllTeachers(){
		return userDao.getAllTeachers();
	}
	
	@Override
	public List<User> getTeachersForClasses(Classes c){
		return userDao.getTeachersForClasses(c.getId());
	}
	
	@Override
	public List<User> getAllUsers(){
		return userDao.getAllUsers();
	}
	
	@Override
	public List<User> getAllExceptCurrent(String login){
		User current = selectUserByLogin(login);
		List<User> all = getAllUsers();
		
		all.remove(current);
		return all;
	}
	
	
}
